package com.example.testrssparser;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

public class FeedService<T> {

	private String url;
	
	ListDataManager dm;
	BaseFeedParser parser;
	
	public FeedService(String url, String file, File dir, BaseFeedParser parser) {
		super();
		this.url = url;
		dm = new ListDataManager(dir, file);
        this.parser = parser;
    }
	
	public InputStream getStreamConnection(ConnectivityManager conMgr) {
		InputStream is = null;
		try {
			NetworkInfo nInfo = conMgr.getActiveNetworkInfo();
	        //notify user you are online
	        if (nInfo == null || !nInfo.isConnected()) {
	        	Log.e("FeedService::getConnection", "user offline");
	        	return null;
	        }
			URL url = new URL(this.url);
			HttpURLConnection con = (HttpURLConnection) url.openConnection();
			is = con.getInputStream();
		} catch (IOException e) {
			Log.e("FeedService::getConnection", e.getMessage());
		}
		return is;
	}
	
	public boolean isCard() {
		return (dm.hasCard() && dm.hasFile());
	}
	
	public List<T> readHttp(ConnectivityManager conMgr) 
			throws CustomParseException, CardException {
		
		InputStream is = getStreamConnection(conMgr);
		if (is == null) {
			return null;
		}
		
        InputStream fis = null;
        List<T> values = null;
        try {
        	if (dm.hasCard()) {
        		dm.createFile(is);
	           	fis = dm.readFile();
	           	values = (List<T>) parser.parse(fis);
	     	} else {
				values = (List<T>) parser.parse(is);
			}
		} finally {
			try {
				if (fis != null) {
					fis.close();
				}
				if (is != null) {
					is.close();
				}
			} catch (IOException e) {
				throw new CardException("FeedService::readHttp IOException", e);
			}
		}
        return values;
	}
	
	public List<T> readFile() throws CustomParseException, CardException {
		List<T> values;
		InputStream is = null;
		try {
			is = dm.readFile();
			values = (List<T>) parser.parse(is);
		} finally {
			try {
				if (is != null) {
					is.close();
				}
			} catch (IOException e) {
				throw new CardException("FeedService::readFile IOException", e);
			}
		}
		return values;
	}
	
}
